package 数组算法;

public class search33 {
    /**
     * 变性的二分法
     *
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        int n = nums.length;
        if (n == 0) {
            return -1;
        }
        if (n == 1) {
            return nums[0] == target ? 0 : -1;
        }
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (nums[mid] == target) {
                return mid;
            }
            // 判断中间值的大于左边的值是否为递增
            if (nums[left] <= nums[mid]) {
                // 左边有序的
                if (nums[left] <= target && target < nums[mid]) {
                    // 再来判断这个值的在哪里
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                // 右边是有序的
                if (nums[mid] < target && target <= nums[n - 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}
